using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace DIS_Client.MainManagers
{
	#region using
	using DevComponents.DotNetBar;
	using DIS_Client.Helpers;
	using System.Data;
	using System.Drawing;
	using System.IO;
	using DIS_Client.DIS_BUS_WS;
	#endregion
	public partial class FrmManagePromotion : Office2007Form
	{
		private DevComponents.DotNetBar.Controls.TextBoxX txtIDItem;
        private int IDToDelete = -1;

		public FrmManagePromotion(bool enableChon = false)
		{
			InitializeComponent();
		}

		private void FrmManageNationalPromotion_Load(object sender, EventArgs e)
		{
			InitGridView();
			InitHiddenFields();
			LoadData();
			dtgvData.ClearSelection();
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			var errorText = "";
			if (!ValidateInput(EnumUpdateMode.DELETE, ref errorText))
			{
				MessageBoxEx.Show(errorText, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			if (MessageBoxEx.Show(CommonHelper.GetMessage("Delete", "Confirm"), "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
			{
				if (ActionDelete())
				{
                    MessageBoxEx.Show(CommonHelper.GetMessage("Delete", "Successful"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
					LoadData();
					btnReset_Click(sender, e);
				}
				else
				{
                    MessageBoxEx.Show(CommonHelper.GetMessage("Delete", "Fail"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			var errorText = "";
			if (!ValidateInput(EnumUpdateMode.UPDATE, ref errorText))
			{
				MessageBoxEx.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
            if (ActionUpdate())
            {
                MessageBoxEx.Show(CommonHelper.GetMessage("Update", "Successful"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadData();
                btnReset_Click(sender, e);
            }
            else
            {
                MessageBoxEx.Show(CommonHelper.GetMessage("Update", "Fail"), "Information", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
		}

		private void btnExit_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void btnReset_Click(object sender, EventArgs e)
		{
            txtIDItem.Text = string.Empty;
            txtItem.Text = string.Empty;
            txtDiscount.Text = string.Empty;
            txtTypePromotion.Text = string.Empty;
		}

		private void dtgvData_CellClick(object sender, DataGridViewCellEventArgs e)
		{
			if (dtgvData.SelectedRows == null || dtgvData.SelectedRows.Count == 0)
				return;
			var selectedItem = dtgvData.SelectedRows[0];
            var item = BusService.Instance.Item_SelectByID(int.Parse(dtgvData.SelectedRows[0].Cells["ID"].Value.ToString()));
            if (item != null)
            {
                txtIDItem.Text = item.ID.ToString();
                txtItem.Text = item.Name;
                txtTypePromotion.Text = dtgvData.SelectedRows[0].Cells["Type"].Value.ToString();

                if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.NATIONAL)
                {
                    var nationalItem = BusService.Instance.NationalPromotion_SelectByIDItem(item.ID);
                    if (nationalItem != null)
                    {
                        txtDiscount.Text = nationalItem.Discount.ToString();
                        IDToDelete = nationalItem.ID;
                    }
                    else
                    {
                        txtDiscount.Text = string.Empty;
                        IDToDelete = -1;
                    }
                }
                else if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.LOCAL)
                {
                    var nationalItem = BusService.Instance.NationalPromotion_SelectByIDItem(item.ID);
                    if (nationalItem != null)
                    {
                        txtDiscount.Text = nationalItem.Discount.ToString();
                        IDToDelete = nationalItem.ID;
                    }
                    else
                    {
                        var localItem = BusService.Instance.LocalPromotion_SelectByIDItemAndIDRestaurant(item.ID, GlobalVariables.g_CurrentUser.IDRestaurant);
                        if (localItem != null)
                        {
                            txtDiscount.Text = localItem.Discount.ToString();
                            IDToDelete = localItem.ID;
                        }
                        else
                        {
                            txtDiscount.Text = string.Empty;
                            IDToDelete = -1;
                        }
                    }

                    if (txtTypePromotion.Text == "National Promotion")
                    {
                        btnDelete.Enabled = false;
                        btnUpdate.Enabled = false;
                    }
                    else
                    {
                        btnDelete.Enabled = true;
                        btnUpdate.Enabled = true;
                    }
                }
            }
		}

		private void InitGridView()
		{
			DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "ID",
				DataPropertyName = "ID",
				Name = "ID",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/4))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "Item",
				DataPropertyName = "Item",
				Name = "Item",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/4))
			};
			dtgvData.Columns.Add(objColumn);
			objColumn = new DataGridViewTextBoxColumn
			{
				HeaderText = "Discount",
				DataPropertyName = "Discount",
				Name = "Discount",
				Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth)*((double)1/4)) - 1
			};
			dtgvData.Columns.Add(objColumn);
            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Type",
                DataPropertyName = "Type",
                Name = "Type",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 4)) - 1
            };
            dtgvData.Columns.Add(objColumn);
		}

		public void InitHiddenFields()
		{
			txtIDItem = new DevComponents.DotNetBar.Controls.TextBoxX
			{
				Name = "txtIDItem",
				Text = ""
			};
			txtIDItem.Visible = false;
		}

        public void LoadPromotionForItems(ref DataTable dt, ItemDTO[] lstItem)
        {
            if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.NATIONAL)
            {
                for (int i = 0; i < lstItem.Length; i++)
                {
                    // Checking item have any record in national promotion
                    var nationalItem = BusService.Instance.NationalPromotion_SelectByIDItem(lstItem[i].ID);
                    if (nationalItem != null)
                    {
                        dt.Rows.Add(lstItem[i].ID, lstItem[i].Name, nationalItem.Discount, "National Promotion");
                    }
                    else
                    {
                        dt.Rows.Add(lstItem[i].ID, lstItem[i].Name, "", "");
                    }
                }
            }
            else if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.LOCAL)
            {
                for (int i = 0; i < lstItem.Length; i++)
                {
                    // Checking item have any record in national promotion
                    var nationalItem = BusService.Instance.NationalPromotion_SelectByIDItem(lstItem[i].ID);
                    if (nationalItem != null)
                    {
                        dt.Rows.Add(lstItem[i].ID, lstItem[i].Name, nationalItem.Discount, "National Promotion");
                    }
                    else
                    {
                        var localItem = BusService.Instance.LocalPromotion_SelectByIDItemAndIDRestaurant(lstItem[i].ID, GlobalVariables.g_CurrentUser.IDRestaurant);
                        if (localItem != null)
                        {
                            // Checking item have any record in local promotion
                            dt.Rows.Add(lstItem[i].ID, lstItem[i].Name, localItem.Discount, "Local Promotion");
                        }
                        else
                        {
                            dt.Rows.Add(lstItem[i].ID, lstItem[i].Name, "", "");
                        }
                    }
                }
            }
        }

		private void LoadData()
		{
			var lstItem = BusService.Instance.Item_SelectAll();
			var dt = new DataTable();
			dt.Columns.Add("ID");
			dt.Columns.Add("Item");
			dt.Columns.Add("Discount");
            dt.Columns.Add("Type");

            // Load promotion for list items
            LoadPromotionForItems(ref dt, lstItem);

			DataView objTimeSheetDV = new System.Data.DataView(dt);
			objTimeSheetDV.AllowNew = false;
			dtgvData.AutoGenerateColumns = false;
			dtgvData.DataSource = objTimeSheetDV;
			dtgvData.ClearSelection();
		}

		private bool ValidateInput(EnumUpdateMode mode, ref string errorText)
		{
			if (mode == EnumUpdateMode.UPDATE)
			{
                if (txtIDItem.Text == "")
                {
                    errorText = "Please select item to update";
                    return false;
                }
			}
            if (mode != EnumUpdateMode.DELETE)
            {
                if (txtDiscount.Text == "")
                {
                    errorText = "Please enter discount";
                    return false;
                }
                else
                {
                    if (!CommonHelper.IsNumeric(txtDiscount.Text))
                    {
                        errorText = "Discount is not numeric";
                        return false;
                    }
                }
            }
            else
            {
                if (IDToDelete == -1)
                {
                    errorText = "There's no selected promotion to delete";
                    return false;
                }
            }
			return true;
		}

		private bool ActionUpdate()
		{
			try
			{
                if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.NATIONAL)
                {
                    var promotion = BusService.Instance.NationalPromotion_SelectByID(int.Parse(txtIDItem.Text));
                    if (promotion == null) // Insert
                    {
                        // Checking promotion for this item is exist in another local promotion
                        var lstLocalPromotion = BusService.Instance.LocalPromotion_SelectByIDItem(int.Parse(txtIDItem.Text));
                        if (lstLocalPromotion != null && lstLocalPromotion.Length > 0)
                        {
                            foreach (var item in lstLocalPromotion)
                            {
                                // Remove all local promotion for this item
                                BusService.Instance.LocalPromotion_Delete(item.ID);
                            }
                        }
                        // Then upgrade this promotion for this item to national promotion
                        promotion = new NationalPromotionDTO
                        {
                            IDItem = int.Parse(txtIDItem.Text),
                            Discount = double.Parse(txtDiscount.Text),
                        };
                        return BusService.Instance.NationalPromotion_Insert(promotion);
                    }
                    else // Update
                    {
                        promotion.IDItem = int.Parse(txtIDItem.Text);
                        promotion.Discount = double.Parse(txtDiscount.Text);
                        return BusService.Instance.NationalPromotion_Update(promotion);
                    }
                }
                else if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.LOCAL)
                {
                    var item = BusService.Instance.LocalPromotion_SelectByID(int.Parse(txtIDItem.Text));
                    if (item == null)
                    {
                        item = new LocalPromotionDTO
                        {
                            IDItem = int.Parse(txtIDItem.Text),
                            IDRestaurant = GlobalVariables.g_CurrentUser.IDRestaurant,
                            Discount = double.Parse(txtDiscount.Text),
                        };
                        return BusService.Instance.LocalPromotion_Insert(item);
                    }
                    else
                    {
                        item.IDItem = int.Parse(txtIDItem.Text);
                        item.IDRestaurant = GlobalVariables.g_CurrentUser.IDRestaurant;
                        item.Discount = double.Parse(txtDiscount.Text);
                        return BusService.Instance.LocalPromotion_Update(item);
                    }
                }
                return false;
			}
			catch
			{
				return false;
			}
		}

		private bool ActionDelete()
		{
			try
			{
                if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.NATIONAL)
                {
                    return BusService.Instance.NationalPromotion_Delete(IDToDelete);
                }
                else if (CommonHelper.GetRole(GlobalVariables.g_CurrentUser) == ROLE.LOCAL)
                {
                    return BusService.Instance.LocalPromotion_Delete(IDToDelete);
                }
                return false;
			}
			catch
			{
				return false;
			}
		}
	}
}